<script setup>
import { ref, reactive, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Delete, View, Loading, Upload, Document, UploadFilled } from '@element-plus/icons-vue'
import { menuAPI, uploadAPI } from '@/api'

// 菜单数据
const menuData = ref([])
const loading = ref(false)
const showSearch = ref(true) // 控制搜索表单显示
const queryRef = ref(null) // 查询表单引用
const importDialogVisible = ref(false)
const uploadedFile = ref(null)
const importLoading = ref(false)
const importUploadRef = ref()
// 查询参数
const queryParams = reactive({
  name: '', // 服务名称搜索
})

// 批量导入
const handleImport = () => {
  uploadedFile.value = null
  importDialogVisible.value = true
  // 确保打开对话框后清理上传组件状态
  setTimeout(() => {
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
  }, 100)
}

// 下载导入模板
const downloadTemplate = async () => {
  try {
    const response = await menuAPI.downloadTemplate()

    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement('a')
      a.href = url
      a.download = '服务菜单导入模板.xlsx'
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)
      ElMessage.success('模板下载成功')
    } else {
      ElMessage.error('模板下载失败')
    }
  } catch (error) {
    ElMessage.error('模板下载失败')
    console.error('模板下载错误:', error)
  }
}

// 提交导入
const handleImportSubmit = async () => {
  if (!uploadedFile.value) {
    ElMessage.warning('请先选择要导入的文件')
    return
  }

  try {
    importLoading.value = true
    const response = await menuAPI.import(uploadedFile.value)
    if (response.code === 200) {
      ElMessage.success('批量导入成功')
      importDialogVisible.value = false
      uploadedFile.value = null
      // 清理上传组件状态
      if (importUploadRef.value) {
        importUploadRef.value.clearFiles()
      }
      getMenuData() // 重新获取菜单数据
    } else {
      ElMessage.error(response.message || '导入失败')
      // 导入失败时重置文件状态，允许重新选择文件
      uploadedFile.value = null
      if (importUploadRef.value) {
        importUploadRef.value.clearFiles()
      }
    }
  } catch (error) {
    ElMessage.error('导入失败')
    console.error('批量导入错误:', error)
    // 导入失败时重置文件状态，允许重新选择文件
    uploadedFile.value = null
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
  } finally {
    importLoading.value = false
  }
}

// 文件变化处理
const handleFileChange = (file) => {
  // 验证文件格式和大小
  const allowedTypes = ['application/vnd.openxmlformats-officedocument.spreadsheetml.sheet', 'application/vnd.ms-excel']

  if (!allowedTypes.includes(file.raw.type)) {
    ElMessage.error('请上传Excel文件（.xlsx 或 .xls 格式）')
    // 清理无效文件
    uploadedFile.value = null
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
    return false
  }

  if (file.raw.size > 10 * 1024 * 1024) {
    ElMessage.error('文件大小不能超过10MB')
    // 清理无效文件
    uploadedFile.value = null
    if (importUploadRef.value) {
      importUploadRef.value.clearFiles()
    }
    return false
  }

  uploadedFile.value = file.raw
  console.log('Selected file:', file)
}

// 文件移除处理
const handleFileRemove = () => {
  uploadedFile.value = null
  console.log('File removed')
}

// 关闭导入对话框
const closeImportDialog = () => {
  importDialogVisible.value = false
  uploadedFile.value = null
  if (importUploadRef.value) {
    importUploadRef.value.clearFiles()
  }
}

// 获取菜单数据
const getMenuData = async () => {
  try {
    loading.value = true
    // 构建请求参数
    const params = {}
    if (queryParams.name.trim()) {
      params.name = queryParams.name.trim()
    }

    const response = await menuAPI.getTree(params)
    if (response && response.code === 200) {
      menuData.value = response.data || []
      // 初始化展开状态
      initExpandState(menuData.value)
    } else {
      ElMessage.error(response?.message || '获取菜单数据失败')
    }
  } catch (error) {
    console.error('获取菜单数据失败:', error)
    ElMessage.error('获取菜单数据失败')
  } finally {
    loading.value = false
  }
}

// 初始化展开状态
const initExpandState = (items) => {
  if (!items) return
  items.forEach((item) => {
    if (!item.hasOwnProperty('expanded')) {
      // 内容项默认折叠，其他类型默认展开
      item.expanded = item.type === 'CONTENT' ? false : true
    }
    if (item.children) {
      initExpandState(item.children)
    }
  })
}

// 展开/收缩功能
const toggleExpand = (item) => {
  item.expanded = !item.expanded
}

// 查询处理
const handleQuery = () => {
  getMenuData()
}

// 重置查询
const resetQuery = () => {
  if (queryRef.value) {
    queryRef.value.resetFields()
  }
  queryParams.name = ''
  getMenuData()
}

// 对话框状态
const dialogVisible = ref(false)
const currentEditItem = ref(null)
const parentMenu = ref(null)
const editForm = reactive({
  name: '',
  type: 'MENU',
  parentId: null,
  status: 1,
  sortOrder: 0,
  description: '', // 简介
  homeImage: '', // 首页图片（用于一级菜单）
  // 内容项详细信息
  contentDetails: {
    serviceTarget: '', // 服务对象
    policyStandard: '', // 政策（服务）标准
    department: '', // 办理科室
    contact: '', // 联系方式
    handleLink: '', // 办理链接
    qrCode: '', // 跳转二维码
    otherInfo: '', // 其他展示
    attachments: [], // 附件列表
    miniProgramCode1: '', // 小程序码1
    miniProgramCode2: '', // 小程序码2
  },
})

// 表单规则
const rules = {
  name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
}

// 添加菜单项
const addMenuItem = (parentItem = null, type = 'MENU') => {
  parentMenu.value = parentItem
  editForm.name = ''
  editForm.type = type
  editForm.parentId = parentItem ? parentItem.id : null
  editForm.status = 1
  editForm.sortOrder = 0
  editForm.description = ''
  editForm.homeImage = '' // 清空首页图片
  // 清空内容项详细信息
  editForm.contentDetails = {
    serviceTarget: '',
    policyStandard: '',
    department: '',
    contact: '',
    handleLink: '',
    qrCode: '',
    otherInfo: '',
    miniProgramCode1: '',
    miniProgramCode2: '',
    attachments: [],
  }
  currentEditItem.value = null
  dialogVisible.value = true
}

// 编辑菜单项
const editMenuItem = (item) => {
  editForm.name = item.name
  editForm.type = item.type
  editForm.parentId = findParentId(item.id)
  editForm.status = item.status || 1
  editForm.sortOrder = item.sortOrder || 0
  editForm.description = item.description || ''
  editForm.homeImage = item.homeImage || '' // 加载首页图片

  // 如果是内容项，加载详细信息
  if (item.type === 'CONTENT') {
    // 解析附件数据，可能是字符串或数组
    let attachments = []
    if (item.contentDetails && item.contentDetails.attachments) {
      if (typeof item.contentDetails.attachments === 'string') {
        try {
          attachments = JSON.parse(item.contentDetails.attachments)
        } catch (error) {
          console.warn('解析附件数据失败:', error)
          attachments = []
        }
      } else if (Array.isArray(item.contentDetails.attachments)) {
        attachments = item.contentDetails.attachments
      }
    }

    // 加载内容项详细信息
    editForm.contentDetails = {
      serviceTarget: item.contentDetails?.serviceTarget || '',
      policyStandard: item.contentDetails?.policyStandard || '',
      department: item.contentDetails?.department || '',
      contact: item.contentDetails?.contact || '',
      handleLink: item.contentDetails?.handleLink || '',
      qrCode: item.contentDetails?.qrCode || '',
      otherInfo: item.contentDetails?.otherInfo || '',
      miniProgramCode1: item.contentDetails?.miniProgramCode1 || '',
      miniProgramCode2: item.contentDetails?.miniProgramCode2 || '',
      attachments: attachments,
    }
  }

  currentEditItem.value = item
  dialogVisible.value = true
}

// 查找父级ID
const findParentId = (itemId) => {
  for (let menu of menuData.value) {
    if (menu.children) {
      for (let child of menu.children) {
        if (child.id === itemId) return menu.id
        if (child.children) {
          for (let grandChild of child.children) {
            if (grandChild.id === itemId) return child.id
          }
        }
      }
    }
  }
  return null
}

// 初始化数据
onMounted(() => {
  getMenuData()
})

// 获取内容详情的辅助函数（兼容新旧数据结构）
const getContentDetail = (item, field) => {
  let value = ''
  if (item.contentDetails && item.contentDetails[field] !== undefined) {
    value = item.contentDetails[field]
  } else if (item[field] !== undefined) {
    value = item[field]
  }

  // 特殊处理附件字段，可能是字符串格式的JSON
  if (field === 'attachments' && value) {
    if (typeof value === 'string') {
      try {
        return JSON.parse(value)
      } catch (error) {
        console.warn('解析附件数据失败:', error)
        return []
      }
    } else if (Array.isArray(value)) {
      return value
    }
    return []
  }

  return value || ''
}

// 检查内容项是否有详细信息
const hasContentDetails = (item) => {
  if (item.type !== 'CONTENT') return false

  const fields = ['serviceTarget', 'policyStandard', 'department', 'contact', 'handleLink', 'qrCode', 'otherInfo']

  // 检查普通字段
  const hasTextFields = fields.some((field) => getContentDetail(item, field))

  // 检查附件
  const attachments = getContentDetail(item, 'attachments')
  const hasAttachments = Array.isArray(attachments) && attachments.length > 0

  return hasTextFields || hasAttachments
}

// 保存菜单项
const saveMenuItem = async () => {
  if (!editForm.name) {
    ElMessage.error('请输入名称')
    return
  }

  try {
    loading.value = true

    const requestData = {
      name: editForm.name,
      type: editForm.type,
      parentId: editForm.parentId,
      status: editForm.status,
      sortOrder: editForm.sortOrder,
      description: editForm.description,
    }

    // 如果是一级菜单，添加首页图片
    if (editForm.type === 'MENU') {
      requestData.homeImage = editForm.homeImage
    }

    // 如果是内容项，添加详细信息
    if (editForm.type === 'CONTENT') {
      // 深拷贝内容详情，避免修改原始数据
      requestData.contentDetails = { ...editForm.contentDetails }

      // 将附件数组转换为字符串格式
      if (Array.isArray(requestData.contentDetails.attachments)) {
        requestData.contentDetails.attachments = JSON.stringify(requestData.contentDetails.attachments)
      }
    }

    let response
    if (currentEditItem.value) {
      // 编辑模式
      response = await menuAPI.update(currentEditItem.value.id, requestData)
      if (response && response.code === 200) {
        ElMessage.success('修改成功')
        // 直接更新本地数据中的对应项目
        updateItemInLocalData(currentEditItem.value.id, requestData)
      } else {
        ElMessage.error(response?.message || '修改失败')
        return
      }
    } else {
      // 添加模式
      response = await menuAPI.create(requestData)
      if (response && response.code === 200) {
        ElMessage.success('添加成功')
        // 添加到本地数据，使用服务器返回的ID或生成临时ID
        const newItem = {
          id: response.data?.id || generateTempId(),
          ...requestData,
          createTime: new Date().toISOString(),
          updateTime: new Date().toISOString(),
          children: requestData.type !== 'CONTENT' ? [] : undefined,
        }
        addItemToLocalData(newItem)
      } else {
        ElMessage.error(response?.message || '添加失败')
        return
      }
    }

    dialogVisible.value = false
  } catch (error) {
    console.error('保存菜单项失败:', error)
    ElMessage.error('操作失败')
  } finally {
    loading.value = false
  }
}

// 更新本地数据中的指定项目
const updateItemInLocalData = (itemId, newData) => {
  const updateInItems = (items) => {
    for (let item of items) {
      if (item.id === itemId) {
        // 更新项目数据，保留原有的ID和children
        Object.assign(item, {
          ...newData,
          id: item.id,
          children: item.children,
          updateTime: new Date().toISOString(),
        })
        return true
      }
      if (item.children && updateInItems(item.children)) {
        return true
      }
    }
    return false
  }

  updateInItems(menuData.value)
}

// 添加项目到本地数据
const addItemToLocalData = (newItem) => {
  if (newItem.parentId) {
    // 添加到指定父级
    const parent = findItemById(newItem.parentId, menuData.value)
    if (parent) {
      if (!parent.children) parent.children = []
      parent.children.push(newItem)
    }
  } else {
    // 添加为一级菜单
    menuData.value.push(newItem)
  }
}

// 生成临时ID（用于新增项目时服务器未返回ID的情况）
const generateTempId = () => {
  return Date.now() + Math.random()
}

// 根据ID查找项目（保留用于编辑时查找父级）
const findItemById = (id, items = null) => {
  const searchItems = items || menuData.value
  const findInItems = (items) => {
    for (let item of items) {
      if (item.id === id) return item
      if (item.children) {
        const found = findInItems(item.children)
        if (found) return found
      }
    }
    return null
  }
  return findInItems(searchItems)
}

// 删除菜单项
const deleteMenuItem = async (item) => {
  try {
    await ElMessageBox.confirm('确认删除此菜单及其所有子项吗？', '删除确认', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning',
    })

    loading.value = true
    const response = await menuAPI.delete(item.id)

    if (response && response.code === 200) {
      ElMessage.success('删除成功')

      // 删除与选中状态相关的逻辑，因为不再需要选中功能

      // 直接更新本地数据，无需重新请求服务器
      removeItemFromLocalData(item.id)
    } else {
      ElMessage.error(response?.message || '删除失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除菜单项失败:', error)
      ElMessage.error('删除失败')
    }
  } finally {
    loading.value = false
  }
}

// 从本地数据中移除指定项目
const removeItemFromLocalData = (itemId) => {
  const removeFromItems = (items) => {
    for (let i = 0; i < items.length; i++) {
      if (items[i].id === itemId) {
        items.splice(i, 1)
        return true
      }
      if (items[i].children && removeFromItems(items[i].children)) {
        return true
      }
    }
    return false
  }

  removeFromItems(menuData.value)
}

// 上传组件引用
const uploadRef = ref()
const uploading = ref(false)

// 二维码上传处理
const handleQRCodeChange = async (file) => {
  try {
    uploading.value = true

    // 验证文件
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif']
    if (!allowedTypes.includes(file.raw.type)) {
      ElMessage.error('请上传JPG、PNG或GIF格式的图片')
      // 清除上传列表
      uploadRef.value?.clearFiles()
      return false
    }

    // 验证文件大小（限制为10MB）
    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.raw.size > maxSize) {
      ElMessage.error('图片大小不能超过10MB')
      uploadRef.value?.clearFiles()
      return false
    }

    // 上传文件到服务器
    const response = await uploadAPI.uploadFile(file.raw, 'qrcode')
    if (response && response.code === 200) {
      editForm.contentDetails.qrCode = response.data.url || response.data
      ElMessage.success('二维码上传成功')
    } else {
      ElMessage.error(response?.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败')
    console.error('二维码上传错误:', error)
  } finally {
    uploading.value = false
    // 清除上传列表，允许下次上传
    uploadRef.value?.clearFiles()
  }
}

// 删除二维码
const handleQRCodeRemove = () => {
  editForm.contentDetails.qrCode = ''
  // 清除上传列表
  uploadRef.value?.clearFiles()
}

// 首页图片上传组件引用
const homeImageUploadRef = ref()

// 首页图片上传处理
const handleHomeImageChange = async (file) => {
  try {
    uploading.value = true

    // 验证文件
    const allowedTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp']
    if (!allowedTypes.includes(file.raw.type)) {
      ElMessage.error('请上传JPG、PNG、GIF或WEBP格式的图片')
      // 清除上传列表
      homeImageUploadRef.value?.clearFiles()
      return false
    }

    // 验证文件大小（限制为5MB）
    const maxSize = 5 * 1024 * 1024 // 5MB
    if (file.raw.size > maxSize) {
      ElMessage.error('图片大小不能超过5MB')
      homeImageUploadRef.value?.clearFiles()
      return false
    }

    // 上传文件到服务器
    const response = await uploadAPI.uploadFile(file.raw, 'home-image')
    if (response && response.code === 200) {
      editForm.homeImage = response.data.url || response.data
      ElMessage.success('首页图片上传成功')
    } else {
      ElMessage.error(response?.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败')
    console.error('首页图片上传错误:', error)
  } finally {
    uploading.value = false
    // 清除上传列表，允许下次上传
    homeImageUploadRef.value?.clearFiles()
  }
}

// 删除首页图片
const handleHomeImageRemove = () => {
  editForm.homeImage = ''
  // 清除上传列表
  homeImageUploadRef.value?.clearFiles()
}

// 附件上传组件引用
const attachmentUploadRef = ref()

// 附件上传处理
const handleAttachmentChange = async (file) => {
  try {
    uploading.value = true

    // 验证文件大小（限制为10MB）
    const maxSize = 10 * 1024 * 1024 // 10MB
    if (file.raw.size > maxSize) {
      ElMessage.error('文件大小不能超过10MB')
      // 清除上传列表
      attachmentUploadRef.value?.clearFiles()
      return false
    }
    // 验证文件类型
    let white_filetype = ['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']
    let white_image = [
      'jpg',
      'jpeg',
      'png',
      'gif',
      'webp',
      'ico',
      'wbmp',
      'fax',
      'net',
      'rp',
      'jfif',
      'jpe',
      'tiff',
      'tif',
    ]
    let white_media = ['mp3', 'wav', 'flac', 'aac', 'mp4', 'avi', 'wmv', 'mov', 'flv']
    let fileType = file.raw.name.split('.').pop().toLowerCase()
    if (!(white_filetype.includes(fileType) || white_image.includes(fileType) || white_media.includes(fileType))) {
      ElMessage.error('请上传支持的文件类型')
      // 清除上传列表
      attachmentUploadRef.value?.clearFiles()
      return false
    }

    // 上传文件到服务器
    const response = await uploadAPI.uploadFile(file.raw, 'attachment')
    if (response && response.code === 200) {
      // 添加到附件列表
      const attachment = {
        id: Date.now() + Math.random(), // 临时ID
        name: file.name,
        url: response.data.url || response.data,
        size: file.raw.size,
        type: file.raw.type,
        uploadTime: new Date().toISOString(),
      }
      editForm.contentDetails.attachments.push(attachment)
      ElMessage.success('附件上传成功')
    } else {
      ElMessage.error(response?.message || '上传失败')
    }
  } catch (error) {
    ElMessage.error('上传失败')
    console.error('附件上传错误:', error)
  } finally {
    uploading.value = false
    // 清除上传列表，允许下次上传
    attachmentUploadRef.value?.clearFiles()
  }
}

// 删除附件
const handleAttachmentRemove = (index) => {
  ElMessageBox.confirm('确认删除此附件吗？', '删除确认', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      editForm.contentDetails.attachments.splice(index, 1)
      ElMessage.success('附件删除成功')
    })
    .catch(() => {
      // 用户取消删除
    })
}

// 格式化文件大小
const formatFileSize = (bytes) => {
  if (bytes === 0) return '0 Bytes'
  const k = 1024
  const sizes = ['Bytes', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + ' ' + sizes[i]
}

// 预览附件
const previewAttachment = (url) => {
  window.open(url, '_blank')
}
</script>

<template>
  <div class="menu-admin">
    <div class="content">
      <!-- 操作栏 -->
      <div class="action-bar">
        <el-button type="primary" @click="addMenuItem(null, 'MENU')" :loading="loading"> 添加一级菜单 </el-button>
        <!-- 搜索表单 -->
        <el-form
          :model="queryParams"
          ref="queryRef"
          :inline="true"
          v-show="showSearch"
          label-width="80px"
          @submit.prevent
        >
          <el-form-item label="服务名称" prop="name">
            <el-input
              v-model="queryParams.name"
              placeholder="请输入服务名称"
              clearable
              @keyup.enter="handleQuery"
              style="width: 300px"
            />
          </el-form-item>
          <el-form-item>
            <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
            <el-button icon="Refresh" @click="resetQuery">重置</el-button>
          </el-form-item>
        </el-form>
        <el-button style="margin-left: auto" @click="handleImport">
          <el-icon><Upload /></el-icon>
          批量导入
        </el-button>
      </div>

      <!-- 树形结构 -->
      <div class="tree-container" v-loading="loading">
        <div class="tree-table">
          <div class="tree-header">
            <div class="tree-column">服务名称</div>
            <div class="tree-column">简介</div>
            <div class="tree-column">首页图片</div>
            <div class="tree-column">操作</div>
          </div>
          <div class="tree-body">
            <template v-for="menu in menuData" :key="menu.id">
              <!-- 一级菜单 -->
              <div class="tree-row" :data-level="0">
                <div class="tree-node">
                  <span class="tree-icon" @click="toggleExpand(menu)" v-if="menu.children && menu.children.length > 0">
                    {{ menu.expanded ? '▼' : '▶' }}
                  </span>
                  <span v-else class="tree-icon-placeholder"></span>
                  <span class="item-name">{{ menu.name }}</span>
                </div>
                <div class="tree-column">
                  <span class="description-text">{{ menu.description || '-' }}</span>
                </div>
                <div class="tree-column">
                  <img v-if="menu.homeImage" :src="menu.homeImage" class="home-image-display" />
                  <span v-else class="no-image-text">无图片</span>
                </div>
                <div class="tree-column">
                  <div class="action-buttons">
                    <span @click="editMenuItem(menu)">✏️</span>
                    <span @click="deleteMenuItem(menu)">🗑️</span>
                    <span @click="addMenuItem(menu, 'SUBMENU')">➕</span>
                  </div>
                </div>
              </div>

              <!-- 二级菜单和内容项 -->
              <template v-if="menu.expanded && menu.children">
                <template v-for="item in menu.children" :key="item.id">
                  <div class="tree-row" :data-level="1">
                    <div class="tree-node">
                      <span class="tree-indent"></span>
                      <span
                        class="tree-icon"
                        @click="toggleExpand(item)"
                        v-if="
                          (item.children && item.children.length > 0) ||
                          (item.type === 'CONTENT' && hasContentDetails(item))
                        "
                      >
                        {{ item.expanded ? '▼' : '▶' }}
                      </span>
                      <span v-else class="tree-icon-placeholder"></span>
                      <span class="item-name">{{ item.name }}</span>
                      <el-tag v-if="item.type === 'CONTENT'" size="small" type="info" class="item-tag">内容项</el-tag>
                    </div>
                    <div class="tree-column">
                      <span class="description-text">{{ item.description || '-' }}</span>
                    </div>
                    <div class="tree-column">
                      <span class="no-image-text">-</span>
                    </div>
                    <div class="tree-column">
                      <div class="action-buttons">
                        <span @click="editMenuItem(item)">✏️</span>
                        <!-- <el-button size="small" @click="editMenuItem(item)">
                          {{ item.type === "CONTENT" ? "编辑" : "重命名" }}
                        </el-button> -->
                        <span @click="deleteMenuItem(item)">🗑️</span>
                        <span v-if="item.type === 'SUBMENU'" @click="addMenuItem(item, 'CONTENT')">➕</span>
                        <!-- <el-button
                          v-if="item.type === 'SUBMENU'"
                          size="small"
                          type="info"
                          @click="addMenuItem(item, 'CONTENT')"
                        >
                          添加
                        </el-button> -->

                        <!-- <el-button
                          size="small"
                          type="danger"
                          @click="deleteMenuItem(item)"
                          >删除</el-button
                        > -->
                      </div>
                    </div>
                  </div>

                  <!-- 内容项详细信息 -->
                  <div
                    v-if="item.type === 'CONTENT' && item.expanded && hasContentDetails(item)"
                    class="content-details-row"
                    :data-level="1"
                  >
                    <div class="content-details">
                      <div v-if="getContentDetail(item, 'serviceTarget')" class="detail-item">
                        <span class="label">服务对象：</span>{{ getContentDetail(item, 'serviceTarget') }}
                      </div>
                      <div v-if="getContentDetail(item, 'policyStandard')" class="detail-item">
                        <span class="label">政策标准：</span>{{ getContentDetail(item, 'policyStandard') }}
                      </div>
                      <div v-if="getContentDetail(item, 'department')" class="detail-item">
                        <span class="label">办理科室：</span>{{ getContentDetail(item, 'department') }}
                      </div>
                      <div v-if="getContentDetail(item, 'contact')" class="detail-item">
                        <span class="label">联系方式：</span>{{ getContentDetail(item, 'contact') }}
                      </div>
                      <div v-if="getContentDetail(item, 'handleLink')" class="detail-item">
                        <span class="label">办理链接：</span>
                        <a :href="getContentDetail(item, 'handleLink')" target="_blank" class="link">
                          {{ getContentDetail(item, 'handleLink') }}
                        </a>
                      </div>
                      <div v-if="getContentDetail(item, 'qrCode')" class="detail-item">
                        <span class="label">二维码：</span>
                        <el-image
                          :src="getContentDetail(item, 'qrCode')"
                          style="width: 60px; height: 60px"
                          fit="cover"
                        />
                      </div>
                      <div v-if="getContentDetail(item, 'otherInfo')" class="detail-item">
                        <span class="label">其他展示：</span>{{ getContentDetail(item, 'otherInfo') }}
                      </div>
                      <div
                        v-if="getContentDetail(item, 'attachments') && getContentDetail(item, 'attachments').length > 0"
                        class="detail-item"
                      >
                        <span class="label">附件：</span>
                        <div class="attachment-display">
                          <div
                            v-for="attachment in getContentDetail(item, 'attachments')"
                            :key="attachment.id"
                            class="attachment-display-item"
                          >
                            <a :href="attachment.url" target="_blank" class="attachment-link" :title="attachment.name">
                              {{ attachment.name }}
                            </a>
                            <span class="file-size">({{ formatFileSize(attachment.size) }})</span>
                          </div>
                        </div>
                      </div>
                    </div>
                  </div>

                  <!-- 三级内容项 -->
                  <template v-if="item.expanded && item.children">
                    <template v-for="content in item.children" :key="content.id">
                      <div class="tree-row" :data-level="2">
                        <div class="tree-node">
                          <span class="tree-indent"></span>
                          <span class="tree-indent"></span>
                          <span class="tree-icon" @click="toggleExpand(content)" v-if="hasContentDetails(content)">
                            {{ content.expanded ? '▼' : '▶' }}
                          </span>
                          <span v-else class="tree-icon-placeholder"></span>
                          <span class="item-name">{{ content.name }}</span>
                          <el-tag size="small" type="info" class="item-tag">内容项</el-tag>
                        </div>
                        <div class="tree-column">
                          <span class="description-text">{{ content.description || '-' }}</span>
                        </div>
                        <div class="tree-column">
                          <span class="no-image-text">-</span>
                        </div>
                        <div class="tree-column">
                          <div class="action-buttons">
                            <span v-if="item.type === 'SUBMENU'" @click="editMenuItem(content)">✏️</span>
                            <span @click="deleteMenuItem(content)">🗑️</span>
                          </div>
                        </div>
                      </div>

                      <!-- 三级内容项详细信息 -->
                      <div
                        v-if="content.expanded && hasContentDetails(content)"
                        class="content-details-row"
                        :data-level="2"
                      >
                        <div class="content-details">
                          <div v-if="getContentDetail(content, 'serviceTarget')" class="detail-item">
                            <span class="label">服务对象：</span>{{ getContentDetail(content, 'serviceTarget') }}
                          </div>
                          <div v-if="getContentDetail(content, 'policyStandard')" class="detail-item">
                            <span class="label">政策标准：</span>{{ getContentDetail(content, 'policyStandard') }}
                          </div>
                          <div v-if="getContentDetail(content, 'department')" class="detail-item">
                            <span class="label">办理科室：</span>{{ getContentDetail(content, 'department') }}
                          </div>
                          <div v-if="getContentDetail(content, 'contact')" class="detail-item">
                            <span class="label">联系方式：</span>{{ getContentDetail(content, 'contact') }}
                          </div>
                          <div v-if="getContentDetail(content, 'handleLink')" class="detail-item">
                            <span class="label">办理链接：</span>
                            <a :href="getContentDetail(content, 'handleLink')" target="_blank" class="link">
                              {{ getContentDetail(content, 'handleLink') }}
                            </a>
                          </div>
                        </div>
                      </div>
                    </template>
                  </template>
                </template>
              </template>
            </template>
          </div>
        </div>
      </div>
    </div>

    <!-- 添加/编辑对话框 -->
    <el-dialog v-model="dialogVisible" :title="currentEditItem ? '编辑' : '添加'" width="600px">
      <el-form :model="editForm" :rules="rules" label-width="100px">
        <el-form-item label="名称" prop="name">
          <el-input v-model.trim="editForm.name" placeholder="请输入名称" />
        </el-form-item>

        <!-- 二级菜单和内容项显示简介输入框 -->
        <el-form-item v-if="editForm.type === 'SUBMENU' || editForm.type === 'CONTENT'" label="简介">
          <el-input
            v-model="editForm.description"
            type="textarea"
            :rows="2"
            placeholder="请输入简介"
            maxlength="200"
            show-word-limit
          />
        </el-form-item>

        <el-form-item label="类型" v-if="!currentEditItem && parentMenu?.type !== 'SUBMENU'">
          <el-radio-group v-model="editForm.type">
            <el-radio value="MENU" v-if="parentMenu == null">一级菜单</el-radio>
            <el-radio value="SUBMENU">二级菜单</el-radio>
            <el-radio value="CONTENT">内容项</el-radio>
          </el-radio-group>
        </el-form-item>

        <!-- 一级菜单首页图片上传 -->
        <el-form-item v-if="editForm.type === 'MENU'" label="首页图片上传">
          <el-upload
            ref="homeImageUploadRef"
            class="home-image-uploader"
            action="#"
            :auto-upload="false"
            :on-change="handleHomeImageChange"
            :on-remove="handleHomeImageRemove"
            :limit="1"
            accept="image/jpeg,image/png,image/gif,image/webp"
            :show-file-list="false"
            :disabled="uploading"
          >
            <el-image
              v-if="editForm.homeImage && !uploading"
              :src="editForm.homeImage"
              class="home-image-preview"
              fit="cover"
            />
            <template v-else>
              <div v-if="uploading" class="uploading-state">
                <el-icon class="is-loading"><Loading /></el-icon>
                <div class="upload-text">上传中...</div>
              </div>
              <template v-else>
                <el-icon class="upload-icon"><Plus /></el-icon>
                <div class="upload-text">点击上传首页图片</div>
              </template>
            </template>
          </el-upload>
          <div v-if="editForm.homeImage" class="home-image-actions">
            <el-button type="danger" size="small" @click="handleHomeImageRemove" :disabled="uploading">
              <el-icon><Delete /></el-icon>
              删除图片
            </el-button>
          </div>
          <div class="upload-tips">
            <span>建议上传首页展示图片，支持JPG、PNG、GIF、WEBP格式，文件大小不超过5MB，建议尺寸200px×150px</span>
          </div>
        </el-form-item>

        <!-- 内容项详细信息表单 -->
        <template v-if="editForm.type === 'CONTENT'">
          <el-divider content-position="left">详细信息</el-divider>
          <el-form-item label="服务对象">
            <el-input
              v-model="editForm.contentDetails.serviceTarget"
              type="textarea"
              :rows="3"
              placeholder="请输入服务对象"
            />
          </el-form-item>
          <el-form-item label="政策标准">
            <el-input
              v-model="editForm.contentDetails.policyStandard"
              type="textarea"
              :rows="2"
              placeholder="请输入政策（服务）标准"
            />
          </el-form-item>
          <el-form-item label="办理科室">
            <el-input v-model="editForm.contentDetails.department" placeholder="请输入办理科室" />
          </el-form-item>
          <el-form-item label="联系方式">
            <el-input v-model="editForm.contentDetails.contact" placeholder="请输入联系方式" />
          </el-form-item>
          <el-form-item label="办理链接">
            <el-input v-model="editForm.contentDetails.handleLink" placeholder="请输入办理链接" />
          </el-form-item>
          <el-form-item label="小程序码1">
            <el-input v-model="editForm.contentDetails.miniProgramCode1" placeholder="请输入小程序码1" />
          </el-form-item>
          <el-form-item label="小程序码2">
            <el-input v-model="editForm.contentDetails.miniProgramCode2" placeholder="请输入小程序码2" />
          </el-form-item>
          <el-form-item label="二维码上传" prop="qrcode">
            <el-upload
              ref="uploadRef"
              class="qrcode-uploader"
              action="#"
              :auto-upload="false"
              :on-change="handleQRCodeChange"
              :on-remove="handleQRCodeRemove"
              :limit="1"
              accept="image/jpeg,image/png,image/gif"
              :show-file-list="false"
              :disabled="uploading"
            >
              <el-image
                v-if="editForm.contentDetails.qrCode && !uploading"
                :src="editForm.contentDetails.qrCode"
                class="qrcode-preview"
                fit="cover"
              />
              <template v-else>
                <div v-if="uploading" class="uploading-state">
                  <el-icon class="is-loading"><Loading /></el-icon>
                  <div class="upload-text">上传中...</div>
                </div>
                <template v-else>
                  <el-icon class="upload-icon"><Plus /></el-icon>
                  <div class="upload-text">点击上传二维码</div>
                </template>
              </template>
            </el-upload>
            <div v-if="editForm.contentDetails.qrCode" class="qrcode-actions">
              <el-button type="danger" size="small" @click="handleQRCodeRemove" :disabled="uploading">
                <el-icon><Delete /></el-icon>
                删除二维码
              </el-button>
            </div>
            <div class="upload-tips">
              <span>支持JPG、PNG、GIF格式，文件大小不超过10MB</span>
            </div>
          </el-form-item>
          <el-form-item label="附件上传">
            <div class="attachment-upload-container">
              <!-- 上传按钮 -->
              <el-upload
                ref="attachmentUploadRef"
                class="attachment-uploader"
                action="#"
                :auto-upload="false"
                :on-change="handleAttachmentChange"
                :multiple="false"
                :show-file-list="false"
                :disabled="uploading"
              >
                <el-button type="primary" :loading="uploading" :disabled="uploading">
                  <el-icon><Plus /></el-icon>
                  {{ uploading ? '上传中...' : '选择文件' }}
                </el-button>
              </el-upload>

              <!-- 附件列表 -->
              <div v-if="editForm.contentDetails.attachments.length > 0" class="attachment-list">
                <div
                  v-for="(attachment, index) in editForm.contentDetails.attachments"
                  :key="attachment.id"
                  class="attachment-item"
                >
                  <div class="attachment-info">
                    <div class="file-details">
                      <div class="file-name" :title="attachment.name">
                        {{ attachment.name }}
                      </div>
                      <div class="file-size">
                        {{ formatFileSize(attachment.size) }}
                      </div>
                    </div>
                  </div>
                  <div class="attachment-actions">
                    <el-button type="primary" size="small" link @click="previewAttachment(attachment.url)">
                      <el-icon><View /></el-icon>
                      预览
                    </el-button>
                    <el-button type="danger" size="small" link @click="handleAttachmentRemove(index)">
                      <el-icon><Delete /></el-icon>
                      删除
                    </el-button>
                  </div>
                </div>
              </div>

              <!-- 上传提示 -->
              <div class="upload-tips">
                <span
                  >微信小程序只支持
                  <p>文档:['doc', 'docx', 'xls', 'xlsx', 'ppt', 'pptx', 'pdf']</p>
                  <p>图片:['jpg','jpeg', 'png', 'gif', 'webp']</p>
                  <p>视频音频:['mp3', 'wav', 'flac', 'aac', 'mp4', 'avi', 'wmv', 'mov', 'flv']</p>
                  单个文件大小不超过10MB</span
                >
              </div>
            </div>
          </el-form-item>
          <el-form-item label="其他展示">
            <el-input
              v-model="editForm.contentDetails.otherInfo"
              type="textarea"
              :rows="3"
              placeholder="请输入其他展示信息"
            />
          </el-form-item>
        </template>
      </el-form>
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="saveMenuItem" :loading="loading">确定</el-button>
      </template>
    </el-dialog>
  </div>
  <!-- 批量导入对话框 -->
  <el-dialog v-model="importDialogVisible" title="批量导入服务" width="400px">
    <div class="import-container">
      <el-upload
        ref="importUploadRef"
        class="upload-demo"
        drag
        action="#"
        :auto-upload="false"
        :on-change="handleFileChange"
        :on-remove="handleFileRemove"
        :limit="1"
        accept=".xlsx,.xls"
      >
        <el-icon class="el-icon--upload"><upload-filled /></el-icon>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <template #tip>
          <div class="el-upload__tip">请上传Excel文件，文件大小不超过10MB</div>
        </template>
      </el-upload>
      <div class="importance">温馨提示：当批量导入服务菜单信息后，仍然需要手动导入图片和视频等附件信息。</div>
      <div class="template-download">
        <el-button @click="downloadTemplate">
          <el-icon><Document /></el-icon>
          下载导入模板
        </el-button>
      </div>
    </div>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="closeImportDialog">取消</el-button>
        <el-button type="primary" :loading="importLoading" @click="handleImportSubmit"> 确认导入 </el-button>
      </span>
    </template>
  </el-dialog>
</template>

<style lang="scss" scoped>
.import-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 10px;
}

.importance {
  color: #f56c6c;
  width: 350px;
}

.template-download {
  text-align: center;
}
.menu-admin {
  padding: 20px;
  display: flex;
  flex-direction: column;

  .content {
    flex: 1;
    overflow: hidden;

    .action-bar {
      display: flex;
      align-items: center;
      margin-bottom: 20px;
      padding-bottom: 20px;
      border-bottom: 1px solid #eee;
    }

    /* 搜索表单样式 */
    .el-form--inline .el-form-item {
      margin-right: 16px;
      margin-bottom: 0;
    }

    .el-form--inline .el-form-item:last-child {
      margin-right: 0;
    }

    .tree-container {
      border: 1px solid #e4e7ed;
      border-radius: 8px;
      background: #fff;
      overflow: auto;

      .tree-table {
        width: 100%;

        .tree-header {
          display: flex;
          padding: 16px;
          border-bottom: 1px solid #e4e7ed;
          font-weight: 600;
          color: #000;
          background: #f5f7fa;

          .tree-column {
            font-weight: bold;
            &:nth-child(1) {
              flex: 1;
              min-width: 300px;
            }
            &:nth-child(2) {
              flex: 1;
              min-width: 150px;
              text-align: center;
            }
            &:nth-child(3) {
              flex: 0 0 120px;
              text-align: center;
            }
            &:nth-child(4) {
              flex: 0 0 200px;
            }
          }
        }

        .tree-body {
          .tree-row {
            display: flex;
            padding: 12px 16px;
            border-bottom: 1px solid #f0f2f5;
            transition: all 0.3s;

            &:hover {
              background-color: #f9f9f9;
            }

            .tree-node {
              flex: 1;
              min-width: 300px;
              display: flex;
              align-items: center;

              .tree-indent {
                width: 20px;
                height: 1px;
              }

              .tree-icon {
                cursor: pointer;
                width: 20px;
                height: 20px;
                display: flex;
                align-items: center;
                justify-content: center;
                font-size: 12px;
                color: #909399;
                transition: all 0.3s;
                margin-right: 8px;

                &:hover {
                  color: #409eff;
                }
              }

              .tree-icon-placeholder {
                width: 20px;
                height: 20px;
                margin-right: 8px;
              }

              .item-name {
                font-weight: 500;
                color: #303133;
                margin-right: 8px;
              }

              .item-tag {
                flex-shrink: 0;
              }
            }

            .tree-column {
              display: flex;
              align-items: center;

              &:nth-child(2) {
                flex: 1;
                min-width: 150px;
                justify-content: center;
                .description-text {
                  font-size: 12px;
                  color: #909399;
                  line-height: 1.4;
                  display: -webkit-box;
                  -webkit-box-orient: vertical;
                  -webkit-line-clamp: 2;
                  line-clamp: 2;
                  overflow: hidden;
                  word-break: break-all;
                }
              }
              &:nth-child(3) {
                flex: 0 0 120px;
                justify-content: center;
              }
              &:nth-child(4) {
                flex: 0 0 200px;
                justify-content: flex-start;
              }
            }

            .action-buttons {
              display: flex;
              gap: 18px;
              flex-wrap: wrap;
              span {
                cursor: pointer;
              }
            }
          }

          .content-details-row {
            background-color: #f8f9fa;
            padding: 8px 16px;
            border-bottom: 1px solid #f0f2f5;
            margin-left: 0;

            &[data-level='1'] {
              margin-left: 40px;
            }

            &[data-level='2'] {
              margin-left: 80px;
            }

            .content-details {
              .detail-item {
                margin-bottom: 6px;
                font-size: 12px;
                color: #606266;
                line-height: 1.5;
                display: flex;
                align-items: flex-start;
                gap: 8px;

                &:last-child {
                  margin-bottom: 0;
                }

                .label {
                  font-weight: 500;
                  color: #303133;
                  flex-shrink: 0;
                  min-width: 80px;
                }

                .link {
                  color: #409eff;
                  text-decoration: none;
                  word-break: break-all;

                  &:hover {
                    text-decoration: underline;
                  }
                }
              }
            }
          }
        }
      }
    }
  }
}

// Element Plus 图标支持
:deep(.el-icon) {
  vertical-align: middle;
}

// 对话框样式优化
:deep(.el-dialog) {
  .el-form-item {
    margin-bottom: 18px;
  }

  .el-divider {
    margin: 12px 0;
  }
}

.qrcode-uploader :deep(.el-upload) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 150px;
  height: 150px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.qrcode-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.qrcode-uploader :deep(.el-upload.is-disabled) {
  cursor: not-allowed;
  opacity: 0.6;
}

.upload-icon {
  font-size: 28px;
  color: #8c939d;
  width: 50px;
  height: 50px;
  line-height: 50px;
  text-align: center;
}

.upload-text {
  color: #8c939d;
  font-size: 14px;
  text-align: center;
  margin-top: 8px;
}

.uploading-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
}

.uploading-state .el-icon {
  font-size: 28px;
  color: var(--el-color-primary);
  margin-bottom: 8px;
}

.qrcode-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.qrcode-actions {
  margin-top: 10px;
  width: 100%;
}

.upload-tips {
  font-size: 12px;
  color: #909399;
  line-height: 1.4;
}

// 首页图片上传相关样式
.home-image-uploader :deep(.el-upload) {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  width: 160px;
  height: 60px;
  border: 1px dashed #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}

.home-image-uploader :deep(.el-upload:hover) {
  border-color: var(--el-color-primary);
}

.home-image-uploader :deep(.el-upload.is-disabled) {
  cursor: not-allowed;
  opacity: 0.6;
}

.home-image-preview {
  width: 100%;
  height: 100%;
  object-fit: cover;
  border-radius: 4px;
}

.home-image-actions {
  margin-top: 10px;
  width: 100%;
}

// 首页图片显示样式
.home-image-display {
  width: 160px;
  height: 60px;
  object-fit: cover;
  border-radius: 4px;
  border: 1px solid #e4e7ed;
}

.no-image-text {
  font-size: 12px;
  color: #c0c4cc;
}

// 附件上传相关样式
.attachment-upload-container {
  width: 100%;
}

.attachment-uploader {
  margin-bottom: 10px;
}

.attachment-list {
  background: #f8f9fa;
  border: 1px solid #e4e7ed;
  border-radius: 6px;
  padding: 12px;
  margin-bottom: 8px;
}

.attachment-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 8px;
  background: #fff;
  border: 1px solid #e4e7ed;
  border-radius: 4px;
  margin-bottom: 8px;
  transition: all 0.3s;

  &:last-child {
    margin-bottom: 0;
  }

  &:hover {
    border-color: #c0c4cc;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.05);
  }
}

.attachment-info {
  display: flex;
  align-items: center;
  flex: 1;
  min-width: 0;
}

.file-icon {
  font-size: 20px;
  margin-right: 8px;
  flex-shrink: 0;
}

.file-details {
  flex: 1;
  min-width: 0;
}

.file-name {
  font-size: 14px;
  color: #303133;
  font-weight: 500;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  line-height: 1.4;
}

.file-size {
  font-size: 12px;
  color: #909399;
  line-height: 1.2;
  margin-top: 2px;
}

.attachment-actions {
  display: flex;
  gap: 8px;
  flex-shrink: 0;
}

// 内容详情中的附件展示样式
.attachment-display {
  display: flex;
  flex-direction: column;
  gap: 6px;
  margin-top: 4px;
}

.attachment-display-item {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 4px 8px;
  background: #f0f2f5;
  border-radius: 4px;
  font-size: 12px;
}

.attachment-link {
  color: #409eff;
  text-decoration: none;
  max-width: 200px;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
  font-weight: 500;

  &:hover {
    text-decoration: underline;
  }
}
</style>
